package com.lsk.apipassenger.service;

import com.lsk.internalcommon.DTO.ResponseResult;
import com.lsk.internalcommon.constant.CommonStatusEnum;
import com.lsk.internalcommon.constant.TokenConstants;
import com.lsk.internalcommon.request.TokenRequest;
import com.lsk.internalcommon.response.TokenResponse;
import com.lsk.internalcommon.util.JwtUtils;
import com.lsk.internalcommon.util.RedisPrefixUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class TokenService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    public ResponseResult refreshToken(String refreshToken){
        //解析refreshToken
        TokenRequest tokenRequest = JwtUtils.checkToken(refreshToken);
        if (tokenRequest==null){
            return ResponseResult.fail(CommonStatusEnum.TOKEN_ERROR.getCode(),CommonStatusEnum.TOKEN_ERROR.getValue());
        }
        String phone = tokenRequest.getPhone();
        String identity = tokenRequest.getIdentity();

        //去redis中获取 原来的refreshToken
        String refreshTokenKey = RedisPrefixUtils.tokenKeyByPhone(phone, identity, TokenConstants.REFRESHTOKEN);
        String redisRefreshToken = redisTemplate.opsForValue().get(refreshTokenKey);
        //生成双token
        if ((redisRefreshToken==null) || (!refreshToken.trim().equals(redisRefreshToken.trim()))){
            return ResponseResult.fail(CommonStatusEnum.TOKEN_ERROR.getCode(),CommonStatusEnum.TOKEN_ERROR.getValue());
        }
        String newAccessToken = JwtUtils.generatorToken(phone, identity, TokenConstants.ACCESSTOKEN);
        String newRefreshToken = JwtUtils.generatorToken(phone, identity, TokenConstants.REFRESHTOKEN);

        String accessTokenKey = RedisPrefixUtils.tokenKeyByPhone(phone,identity,TokenConstants.ACCESSTOKEN);

        redisTemplate.opsForValue().set(accessTokenKey,newAccessToken,30,TimeUnit.DAYS);
        redisTemplate.opsForValue().set(refreshTokenKey,newRefreshToken,31, TimeUnit.DAYS);

        TokenResponse tokenResponse = new TokenResponse();
        tokenResponse.setAccessToken(newAccessToken);
        tokenResponse.setRefreshToken(newRefreshToken);
        return ResponseResult.success(tokenResponse);
    }
}
